//
//  CYReleaseVC.m
//  CreditAddressBook
//
//  Created by Lee on 15/7/27.
//  Copyright (c) 2015年 Lee. All rights reserved.
//  违约发布

#import "CYReleaseVC.h"
#import "CYDatePickerView.h"
#import "CYMeHttpTool.h"
#import "LEImagePicker.h"
#import "LEUnitView.h"
#import "CYCreditTool.h"
#import "CYUploadProgress.h"
#import "CYProgress.h"
#import "CYLoginHttpTool.h"
#import "CYUser.h"
#import "LEUUID.h"
#import "CYDefaultRecord.h"
#import "MJExtension.h"
#import "LEUnitCell.h"
#import "UIInfomationView.h"
#import "MBProgressHUD+MJ.h"
#import "CYEscape.h"
#import "UIImageView+WebCache.h"
#import "CYDefaultRecordPics.h"
#import "UIButton+WebCache.h"
#import "CYMyRelease.h"
#import "CYABTool.h"
#import "CYPersonReleaseVC.h"
#import "CYReleaseVC.h"
#import "CYTool.h"

@interface CYReleaseVC ()<UIScrollViewDelegate, CYDatePickerViewDelegate,UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UILabel *websiteLabel;
@property (weak, nonatomic) IBOutlet UILabel *appNameLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewHeight;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *cover;
@property (weak, nonatomic) IBOutlet UIButton *lendDateBtn;
@property (weak, nonatomic) IBOutlet UIButton *shouldPayDateBtn;
@property (weak, nonatomic) IBOutlet UIButton *actualPayDateBtn;



@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UITextField *idCardTF;
@property (weak, nonatomic) IBOutlet UITextField *lendTF;
@property (weak, nonatomic) IBOutlet UITextField *addressTF;
@property (weak, nonatomic) IBOutlet UITextField *registerAddressTF;
@property (weak, nonatomic) IBOutlet UITextView *notesTextV;
@property (weak, nonatomic) IBOutlet UIButton *idCardZBtn;
@property (weak, nonatomic) IBOutlet UIButton *idCardFBtn;
@property (weak, nonatomic) IBOutlet UITextField *QQTF;


@property (weak, nonatomic) IBOutlet UIView *compactView;//合同、借条
@property (weak, nonatomic) IBOutlet UIView *certificateView;//凭证
@property (weak, nonatomic) IBOutlet UIView *otherView;

@property (weak, nonatomic) IBOutlet UIView *progressView;//进度条View
@property (weak, nonatomic) IBOutlet UIView *progressViewF;

@property (weak, nonatomic) CYDatePickerView *datePicker;
@property (strong, nonatomic) NSDate *lendDate;
@property (strong, nonatomic) NSDate *shouldPayDate;
@property (strong, nonatomic) NSDate *payDate;
@property (strong, nonatomic) NSString *lendDateStr;
@property (strong, nonatomic) NSString *shouldPayDateStr;
@property (strong, nonatomic) NSString *payDateStr;

@property (strong, nonatomic) LEImagePicker *imagePicker;

@property (strong, nonatomic) NSMutableArray *compactImageUrls;//合同、借条图片地址
@property (strong, nonatomic) NSMutableArray *certificateUrls;//凭证图片地址
@property (strong, nonatomic) NSMutableArray *otherImageUrls;//其他凭证图片地址
@property (strong, nonatomic) NSString *idCardZImageUrl;//身份证正面
@property (strong, nonatomic) NSString *idCardFImageUrl;//身份证反面

@property (weak, nonatomic) LEUnitView *compactUnitView;//借条合同的UnitView
@property (weak, nonatomic) LEUnitView *certificateUnitView;
@property (weak, nonatomic) LEUnitView *otherUnitView;
@end

@implementation CYReleaseVC

- (NSMutableArray *)compactImageUrls {
    if (!_compactImageUrls) {
        _compactImageUrls = [NSMutableArray array];
    }
    return _compactImageUrls;
}

- (NSMutableArray *)certificateUrls {
    if (!_certificateUrls) {
        _certificateUrls = [NSMutableArray array];
    }
    return _certificateUrls;
}

- (NSMutableArray *)otherImageUrls {
    if (!_otherImageUrls) {
        _otherImageUrls = [NSMutableArray array];
    }
    return _otherImageUrls;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
     _nameTF.delegate = self;
     _QQTF.delegate = self;
     _phoneTF.delegate = self;
     _idCardTF.delegate = self;
     _lendTF.delegate = self;
     _addressTF.delegate = self;
     _registerAddressTF.delegate = self;
     
    self.scrollView.delegate = self;
    
    CYDatePickerView *picker = [[CYDatePickerView alloc] initWithFrame:CGRectMake(0, CYScreeSize.height, 0, 0)];
    [self.view addSubview:picker];
    picker.delegate = self;
    self.datePicker = picker;
    
    self.imagePicker = [[LEImagePicker alloc] init];
    
    [self uploadImageForCompact];
    [self uploadImageForCertificate];
    [self uploadImageForOther];
    
    [self setupDefaultRecord];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
     //主要是[receiver resignFirstResponder]在哪调用就能把receiver对应的键盘往下收
     [_QQTF resignFirstResponder];
     [_nameTF resignFirstResponder];
     [_phoneTF resignFirstResponder];
     [_idCardTF resignFirstResponder];
     [_lendTF resignFirstResponder];
     [_addressTF resignFirstResponder];
     [_registerAddressTF resignFirstResponder];
     return YES;
     
}


#pragma mark - 日期选择
/**
 *  借款时间
 */
- (IBAction)lendDate:(id)sender {
    self.cover.hidden = NO;
    [UIView animateWithDuration:.4 animations:^{
        self.datePicker.transform = CGAffineTransformMakeTranslation(0, -self.datePicker.height);
    }];
    
    self.datePicker.minDate = nil;
    self.datePicker.maxDate = self.shouldPayDate ? self.shouldPayDate : self.payDate;//优先返回本该还款时间，maxDate<本该还款时间<=实际还款时间
    
    __weak typeof (self)weakSelf = self;
    [self.datePicker selectedDate:^(NSDate *date, NSString *dateStr) {
        UIButton *btn = (UIButton *)sender;
        [btn setTitle:dateStr forState:UIControlStateNormal];
        
        weakSelf.lendDate = date;
        weakSelf.lendDateStr = dateStr;
        CYLog(@"%@", dateStr);
    }];
    [self.view.window endEditing:YES];
}

/**
 *  本该还款时间
 *  借款时间<本该还款时间<=实际还款时间
 */
- (IBAction)shouldPayDate:(id)sender {
    self.cover.hidden = NO;
    [UIView animateWithDuration:.4 animations:^{
        self.datePicker.transform = CGAffineTransformMakeTranslation(0, -self.datePicker.height);
    }];
    
    self.datePicker.minDate = self.lendDate;
    self.datePicker.maxDate = self.payDate;
    
    __weak typeof (self)weakSelf = self;
    [self.datePicker selectedDate:^(NSDate *date, NSString *dateStr) {
        UIButton *btn = (UIButton *)sender;
        [btn setTitle:dateStr forState:UIControlStateNormal];
        
        weakSelf.shouldPayDate    = date;
        weakSelf.shouldPayDateStr = dateStr;
        CYLog(@"%@", dateStr);
    }];
    [self.view.window endEditing:YES];
}

/**
 *  实际还款时间
 */
- (IBAction)actualPayDate:(id)sender {
    self.cover.hidden = NO;
    [UIView animateWithDuration:.4 animations:^{
        self.datePicker.transform = CGAffineTransformMakeTranslation(0, -self.datePicker.height);
    }];
    
    self.datePicker.minDate = self.shouldPayDate ? self.shouldPayDate : self.lendDate;
    self.datePicker.maxDate = [NSDate date];
    
    __weak typeof (self)weakSelf = self;
    [self.datePicker selectedDate:^(NSDate *date, NSString *dateStr) {
        UIButton *btn = (UIButton *)sender;
        [btn setTitle:dateStr forState:UIControlStateNormal];
        
        weakSelf.payDate    = date;
        weakSelf.payDateStr = dateStr;
        CYLog(@"%@", dateStr);
    }];
    [self.view.window endEditing:YES];
}

#pragma mark - CYDatePickerViewDelegate
- (void)datePickerView:(CYDatePickerView *)view date:(NSDate *)date dateFormatter:(NSString *)formatter {
    //隐藏遮盖
    self.cover.hidden = YES;
    
    //退下日期选中框
    [UIView animateWithDuration:.3 animations:^{
        self.datePicker.transform = CGAffineTransformIdentity;
    }];
}

- (IBAction)coverClick:(UIButton *)sender {
    sender.hidden = YES;
    [UIView animateWithDuration:.3 animations:^{
        self.datePicker.transform = CGAffineTransformIdentity;
    }];
}

/**
 *  提交
 */
- (IBAction)submit:(UIBarButtonItem *)sender {
     
     if (_phoneTF.text.length>0) {
          BOOL a = [CYTool isphoneNumber:_phoneTF.text];
          if (a) {
               //是
               
               
          }else{
               //不是
               CYAlertView(@"请输入正确的手机号");
               return;
               
          }

     }
     if (_idCardTF.text.length>0) {
          BOOL b = [CYTool isidcard:_idCardTF.text];
          if (b) {
               //是
               
               
          }else{
               //不是
               CYAlertView(@"请输入正确的身份证号");
               return;
               
          }
     }
     

    if ([self checkSuccess]) {
        CYUser *user = [CYLoginHttpTool userData].user;
//        CYUser *a    = [[CYUser alloc] init];
//        a.userId     = [CYEscape escapeWithString:user.userId];
        
        CYDefaultRecord *defaultRecord = [CYDefaultRecord new];
        if (self.record) {
            defaultRecord.defaultRecordId = self.record.defaultRecordId;
        }
        defaultRecord.name            = self.nameTF.text;
        defaultRecord.phone           = self.phoneTF.text;
        defaultRecord.certificateNo   = self.idCardTF.text;
        defaultRecord.amountPrice     = self.lendTF.text;
        defaultRecord.homeAddress     = self.addressTF.text;
        defaultRecord.memo            = self.notesTextV.text;
        defaultRecord.registerAddress = self.registerAddressTF.text;
        defaultRecord.lendTime        = self.lendDateStr;
        defaultRecord.startTime       = self.shouldPayDateStr;
        defaultRecord.endTime         = self.payDateStr;
        defaultRecord.userId = user.userId;
        defaultRecord.userName = user.nickName;
        
        NSDictionary *params = defaultRecord.keyValues;
        
        NSMutableDictionary *p      = [NSMutableDictionary dictionaryWithDictionary:params];
        p[@"certificateNoZAddress"] = self.idCardZImageUrl;
        if (self.idCardFImageUrl) {
            p[@"certificateNoFAddress"] = self.idCardFImageUrl;
        }
        p[@"contactAddress"] = self.compactImageUrls;
        p[@"receiptAddress"] = self.certificateUrls;
        if (self.otherImageUrls && self.otherImageUrls.count) {
            p[@"otherAddress"] = self.otherImageUrls;
        }
        p[@"token"] = user.token;
        if (_QQTF.text&&_QQTF.text.length) {
            p[@"qq"] = _QQTF.text;
        }
        
        CYLog(@"%@", p);
        [UIInfomationView showAlertViewWithTitle:@"违约信息发布注意事项及承诺" message:@"\n1.平台违约信息发布免费。\n2.对于成功通过平台调解，催收的欠款，平台将收取3%的管理费。\n3.信息发布者独立承担违约信息真实性和完整性责任，因证据材料虚假而导致的一切后果，由信息发布者自行承担。\n\n本人承诺以上内容及所附其他材料的真实性，如有虚假，由此引发的一切后果由本人承担。" cancelButtonTitle:@"取消" otherButtonTitles:@[@"同意并提交"] clickAtIndex:^(NSInteger buttonIndex) {
            
            if (buttonIndex == CYIndexSecond) {
                [MBProgressHUD showMessage:@"提交中" toView:self.view];
                [CYCreditTool saveDefaultRecordWithParams:p success:^(NSString *message) {
                    
                    [MBProgressHUD hideHUDForView:self.view];
                    [MBProgressHUD showSuccess:@"上传成功"];
                    
                    
//                    CYPersonReleaseVC *release = [self.storyboard instantiateViewControllerWithIdentifier:@"CYPersonReleaseVC"];
                    CYMyRelease *release = [self.storyboard instantiateViewControllerWithIdentifier:@"CYMyRelease"];
                    if (self.record) {//
                        release.backStyle = CYBackStyleTreble;
                    } else {
                        if (self.pushStyle == CYPushStyleFromSetting) {
                            release.backStyle = CYBackStyleDouble;
                        } else {
                            release.backStyle = CYBackStyleInterval;
                        }
                    }
                    
                    CYPersonReleaseVC *person  = [[CYPersonReleaseVC alloc]init];
                    //跳转到我的发布页面
                    [self.navigationController pushViewController:person animated:YES];
                } failure:^(NSError *error) {
                    [MBProgressHUD hideHUDForView:self.view];
                    if (error.code == CYErrorCodeNoLogin) {
                        [MBProgressHUD showError:error.userInfo[@"message"]];
                        [CYLoginHttpTool logoutWithController:self];
                    }
                }];
            }
        }];
        
    }
}

- (BOOL)checkSuccess {
    if (!self.certificateUrls.count || !self.compactImageUrls.count || !self.idCardZImageUrl) {
        CYAlertView(@"请上传相关图片");
        return NO;
    } else if (CYStringEqualTo(self.nameTF.text, @"")) {
        CYAlertView(@"请输入违约人姓名");
        return NO;
    } else {
        if (self.idCardTF.text && !self.idCardTF.text.isEmpty) {
            NSRange range = [self.idCardTF.text rangeOfString:@"^(\\d{18,18}|\\d{15,15}|\\d{17,17}x)$" options:NSRegularExpressionSearch];
            if (range.location == NSNotFound) {
                CYAlertView(@"请输入正确的身份证号码");
                return NO;
            }
        } else {
            CYAlertView(@"请输入身份证号码");
            return NO;
        }
    }
    return YES;
}

#pragma mark - 图片上传
/**
 *  身份证正反面上传
 */
- (IBAction)idCard:(UIButton *)sender {
    CYProgress *pro = [[CYProgress alloc] init];
    CYUploadProgress *progress = [CYUploadProgress uploadProgress:pro];
    progress.hidden = YES;
    if (sender.tag) {
        [self.progressViewF addSubview:progress];
    } else {
        [self.progressView addSubview:progress];
    }
    progress.bounds = self.progressView.bounds;
    pro.hiddenMessageView = YES;
    
    [self.imagePicker showInController:self handler:^(UIImage *image) {
        [sender setImage:image forState:UIControlStateNormal];
        __block UIButton *btn = sender;
        [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
            
            if (btn.tag) {
                self.idCardFImageUrl = imageUrl;
            } else {
                self.idCardZImageUrl = imageUrl;
            }
            
            pro.hiddenMessageView = NO;
            pro.success = YES;
            progress.progress = pro;
            
        } failure:^(NSError *error) {
            [btn setImage:[UIImage imageNamed:@"icon_btn_add_unpressed"] forState:UIControlStateNormal];
            
            pro.hiddenMessageView = NO;
            pro.success = NO;
            progress.progress = pro;
        } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            CGFloat a = totalBytesWritten;
            CGFloat b = totalBytesExpectedToWrite;
            progress.hidden = NO;
            pro.uploadProgress = a/b;
            progress.progress = pro;
        }];
    }];
}

/**
 *  合同、借条
 */
- (void)uploadImageForCompact {
    
    self.compactUnitView = [self imageScrollView:self.compactView block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
        [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
            [self.compactImageUrls addObject:imageUrl];
            
            cell.ratio = 1;
        } failure:^(NSError *error) {
            //删除
            [unitView deleteLastCell];
        } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            
            CGFloat a = totalBytesWritten;
            CGFloat b = totalBytesExpectedToWrite;
            cell.ratio = a/b - .01;
        }];
    }];
}

/**
 *  凭证
 */
- (void)uploadImageForCertificate {
    
    self.certificateUnitView = [self imageScrollView:self.certificateView block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
        
        [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
            [self.certificateUrls addObject:imageUrl];
            
            cell.ratio = 1;
        } failure:^(NSError *error) {
            //删除
            [unitView deleteLastCell];
        } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            
            CGFloat a = totalBytesWritten;
            CGFloat b = totalBytesExpectedToWrite;
            cell.ratio = a/b - .01;
        }];
    }];
}

/**
 *  其他
 */
- (void)uploadImageForOther {
    self.otherUnitView = [self imageScrollView:self.otherView block:^(LEUnitView *unitView, LEUnitCell *cell, UIImage *image) {
        [CYCreditTool uploadPicImage:image success:^(NSString *imageUrl) {
            [self.otherImageUrls addObject:imageUrl];
            cell.ratio = 1;
        } failure:^(NSError *error) {
            //删除
            [unitView deleteLastCell];
        } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
            CGFloat a = totalBytesWritten;
            CGFloat b = totalBytesExpectedToWrite;
            cell.ratio = a/b - .01;
        }];
    }];
}

/**
 *  添加图片选择器LEUnitView
 *
 *  @param view  添加目标view
 *  @param block 添加完成后的block
 */
- (LEUnitView *)imageScrollView:(UIView *)view block:(void (^)(LEUnitView *unitView, LEUnitCell *cell, UIImage *image))block {
    
    [view layoutIfNeeded];
    LEUnitView *unitView = [[LEUnitView alloc] initWithFrame:(CGRect){CGPointZero, view.frame.size}];
    [view addSubview:unitView];
    
    __weak typeof (unitView)weakUnitView = unitView;
    __weak typeof (self)weakSelf = self;
    [unitView addButtonClick:^{
        
        [weakSelf.imagePicker showInController:self handler:^(UIImage *image) {
            
            LEUnitCell *cell = [weakUnitView addNewUnit:image withName:@""];
            if (block) {
                block(weakUnitView, cell, image);
            }
        }];
    }];
    return unitView;
}

/**
 *  身份证上传进度百分比
 */
- (CYUploadProgress *)setupProgressView {
    
    CYProgress *pro            = [[CYProgress alloc] init];
    CYUploadProgress *progress = [CYUploadProgress uploadProgress:pro];
    progress.hidden            = YES;
    [self.progressView addSubview:progress];
    progress.bounds            = self.progressView.bounds;
    pro.hiddenMessageView      = YES;
    
    return progress;
}

#pragma mark - scrollViewDidScroll
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view.window endEditing:YES];
}

#pragma mark -
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view.window endEditing:YES];
}

#pragma mark - setupDefaultRecord
/**
 *  编辑时设置默认值
 */
- (void)setupDefaultRecord {
    if (self.record) {
        self.nameTF.text            = self.record.name;
        self.phoneTF.text           = self.record.phone;
        self.idCardTF.text          = self.record.certificateNo;
        self.lendTF.text            = CYStringFormat(@"%@", self.record.amountPrice);
        self.addressTF.text         = self.record.homeAddress;
        self.registerAddressTF.text = self.record.registerAddress;
        self.notesTextV.text        = self.record.memo;
        
        CYUser *user = [CYLoginHttpTool userData].user;
        [CYCreditTool defaultPicsWithParams:@{@"id": self.record.defaultRecordId, @"userId": user.userId, @"token": user.token} success:^(CYDefaultRecordPics *defrs) {
            
            [self.idCardZBtn sd_setImageWithURL:CYURLWithService(defrs.idCardZImageUrl) forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"putao_icon_quick_replace_s"]];
            if (defrs.idCardFImageUrl) {
                [self.idCardFBtn sd_setImageWithURL:CYURLWithService(defrs.idCardFImageUrl) forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"putao_icon_quick_replace_s"]];
            }
            
            self.idCardZImageUrl = defrs.idCardZImageUrl;//身份证正面
            self.idCardFImageUrl = defrs.idCardFImageUrl;//身份证反面
            //合同
            [self loadImageWithUnitView:self.compactUnitView urls:defrs.compactImageUrls];
            [self.compactImageUrls addObjectsFromArray:defrs.compactImageUrls];
            //凭证
            [self loadImageWithUnitView:self.certificateUnitView urls:defrs.certificateUrls];
            [self.certificateUrls addObjectsFromArray:defrs.certificateUrls];
            //其他
            if (defrs.otherImageUrls) {
                [self loadImageWithUnitView:self.otherUnitView urls:defrs.otherImageUrls];
                [self.otherImageUrls addObjectsFromArray:defrs.otherImageUrls];
            }
            
        } failure:^(NSError *error) {
            
        }];
    }
}

/**
 *  加载UnitView中显示的图片
 *
 *  @param urls
 */
- (void)loadImageWithUnitView:(LEUnitView *)view urls:(NSArray *)urls {
    for (NSString *url in urls) {
        __block LEUnitCell *cell = [view addNewUnit:nil withName:nil];
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:CYURLWithService(url) options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
            CGFloat a = receivedSize;
            CGFloat b = expectedSize;
            cell.ratio = a/b;
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            cell.image = image;
        }];
    }
}

- (void)dealloc {
    CYLog(@"违约发布销毁");
}
@end
